<template>
  <view>
    <view v-if="props.title" class="cb-input-title">{{ props.title }}</view>
    <!-- 插槽模式 -->
    <view v-if="props.isSlot" class="input-slot">
      <input :value="model" :placeholder="props.placeholder" :type="props.type" placeholder-style="color: #9ca5ad;"
             @input="onInput" />
      <view class="right-name">
        <slot></slot>
      </view>
    </view>
    <view v-else-if="props.type === 'idCard'" class="input-id-card">
      <input v-model="idCard.birth" :placeholder="$t('apply.birth')" type="number" placeholder-style="color: #9ca5ad;"
             class="cb-input" @input="onIdCardInput(0)" />
      <text class="dash">-</text>
      <input v-model="idCard.name" :placeholder="$t('apply.idCard.name2')" type="number"
             placeholder-style="color: #9ca5ad;" class="cb-input" @input="onIdCardInput(1)" />
    </view>
    <view v-else>
      <picker v-if="IS_SELECT.includes(props.type)" @change="bindPickerChange" :value="index"
              :range="listValue[props.type]">
        <view v-if="IS_SELECT.includes(props.type)" class="cb-selection">
          <view :class="company ? 'selection-active' : 'selection-inactive'">
            {{ company || props.placeholder }}
          </view>
          <uni-icons type="forward" size="18" style="color: #9ca5ad"></uni-icons>
        </view>
      </picker>
      <picker v-else-if="props.type === 'date'" mode="date" :value="model" :start="startDate" :end="endDate"
              @change="bindDateChange">
        <view class="cb-selection">
          <view :class="model || company ? 'selection-active' : 'selection-inactive'">
            {{ model || company || props.placeholder }}
          </view>
          <uni-icons type="forward" size="18" style="color: #9ca5ad"></uni-icons>
        </view>
      </picker>
      <input v-else :value="model" :placeholder="props.placeholder" :type="props.type"
             placeholder-style="color: #9ca5ad;" class="cb-input" @input="onInput" />
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { onLoad } from '@dcloudio/uni-app'
import { getSelectData } from '@/api'

const { t } = useI18n()

const model = defineModel({
  type: [String, Number],
  default: ''
})

const props = defineProps(['placeholder', 'type', 'title', 'isSlot'])
const emit = defineEmits(['change'])

/**
 * communication: 通信公司
 * funds: 资金
 * occupation: 职业
 * switch: 开关
 * marriage：婚姻
 * housingType：住房类型
 * repaymentClass：还款方式
 * deadline：贷款期限选择
 * purpose：企业资金用途
 * loanProduct：贷款产品
 */
const IS_SELECT = ['communication', 'funds', 'occupation', 'switch', 'marriage', 'housingType', 'repaymentClass', 'deadline', 'entType', 'purpose', 'loanProduct']

/** 是否下标+1 */
const IS_INDEX = ['occupation', 'marriage', 'housingType', 'repaymentClass', 'entType']

const onInput = ({ detail }) => {
  model.value = detail.value
}

const listValue = ref({
  communication: ['SKT', 'KT', 'LG U+', 'SKT 알뜰폰', 'KT 알뜰폰', 'LG U+ 알뜰폰'],
  switch: ['없음', '네'],
  occupation: [
    t('apply.occupation.work'),
    t('apply.occupation.individual'),
    t('apply.occupation.unemployed'),
    t('apply.occupation.student'),
    t('apply.house.type.4')
  ],
  marriage: [
    t('apply.marriage.single'),  // 1
    t('apply.marriage.married'), // 2
    // t('apply.marriage.divorced'), // 3
    t('apply.marriage.widowed') // 4
  ],
  housingType: [
    t('apply.house.type.1'),
    t('apply.house.type.2'),
    t('apply.house.type.3'),
    t('apply.house.type.4')
  ],
  repaymentClass: [
    t('apply.repayment.monthly1'),
    t('apply.repayment.monthly2'),
  ],
  entType: [
    t('enterprise.type1'),
    t('enterprise.type2'),
    t('enterprise.type3'),
    // t('enterprise.type4')
  ],
  loanProduct: [
    t('loan.product.name1'),
    t('loan.product.name2'),
    t('loan.product.name3'),
  ],
  funds: [],
  deadline: [],
  purpose: []
})
const index = ref(0)
const array = ref(listValue.value[props.type])
const company = ref('')
const bindPickerChange = ({ detail }) => {
  company.value = array.value[detail.value]

  // const data = {
  //   communication: company.value,
  //   funds: loansMoneyConfig.value?.[detail.value].id,
  //   switch: detail.value,
  //   occupation: detail.value + 1
  // }

  let data = detail.value
  if (['funds', 'purpose'].includes(props.type)) {
    data = loansMoneyConfig.value[detail.value].id
  }

  if (IS_INDEX.includes(props.type)) {
    data = detail.value + 1
  }

  if (props.type === 'deadline') {
    data = loansMoneyConfig.value[detail.value].loanTerm
  }

  if (props.type === 'loanProduct') {
    data = company.value
  }

  emit('change', data)
}

/** 获取资金用途 */
const loansMoneyConfig = ref([])
const getList = async () => {
  const res = await getSelectData()
  const keyName = {
    funds: 'loansMoneyConfig',
    deadline: 'loanRepaymentConfig',
    purpose: 'loansMoneyConfigCompanse'
  }[props.type]

  const isShow = ['funds', 'purpose'].includes(props.type)
  const resList = res[keyName]
  loansMoneyConfig.value = resList
  const list = resList.map((item) => {
    return isShow ? item.configName : item.loanTerm + t('repayment.month')
  })

  listValue.value[props.type] = list
  array.value = list
  if (model.value) {
    if (isShow) {
      const { configName } = resList.find(v => v.id === model.value)
      company.value = configName
    } else {
      const { loanTerm } = resList.find(v => v.loanTerm === model.value)
      company.value = loanTerm + t('repayment.month')

    }

  }
}

const startDate = computed(() => getDate('start'))
const endDate = computed(() => getDate('end'))
const bindDateChange = ({ detail }) => {
  company.value = detail.value
  emit('change', company.value)
}

const getDate = (type) => {
  const date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()

  if (type === 'start') {
    year = year - 10
  } else if (type === 'end') {
    year = year + 10
  }
  month = month > 9 ? month : '0' + month
  day = day > 9 ? day : '0' + day
  return `${year}-${month}-${day}`
}


/** 身份证 */
const idCard = reactive({
  // 生日
  birth: '',
  // 后半部分
  name: ''
})
const onIdCardInput = () => {
  if (idCard.birth && idCard.name) {
    model.value = `${idCard.birth}-${idCard.name}`
  }
}
/** 身份证结束 */

onLoad(() => {
  // 资金用途，贷款期限
  if (['deadline', 'funds', 'purpose'].includes(props.type)) {
    getList()
  } else {
    if (String(model.value) && IS_SELECT.includes(props.type)) {
      if (IS_INDEX.includes(props.type)) {
        company.value = array.value[model.value - 1]
        return
      }
      company.value = array.value[model.value]
    }

    // 身份证号码赋值
    if (props.type === 'idCard' && model.value) {
      idCard.birth = model.value.split('-')[0]
      idCard.name = model.value.split('-')[1]
    }

  }
})
</script>

<style lang="scss" scoped>
.input-slot {
  border-radius: 64rpx;
  border: 2rpx solid #666666;
  padding: 28rpx 48rpx;
  display: flex;
  align-items: baseline;
  justify-content: space-between;

  input {
    flex: 1;
  }

  .right-name {
    font-size: 32rpx;
    padding-left: 24rpx;
  }
}

.input-id-card {
  display: flex;
  align-items: baseline;

  .dash {
    font-weight: 700;
    margin: 0 20rpx;
  }
}
</style>
